package com.zhx.threadcoreknowledge.stopthread;

/**
 * @author ：zhanghaixuan
 * @date ：Created in 2019-09-29 09:36
 * 用途         ： 生产中最佳实践 catch住了InterruptExecption之后的优先选择,在方法签名中抛出异常,
 * 那么在run()就会强制try/catch
 */
public class RightWayStopThreadInProd implements Runnable{

    @Override
    public void run() {
        while(true){
            System.out.println("go");
            try {
                throwInMethod();
            } catch (InterruptedException e) {
                /**
                 * 这里才是正确响应中断的地方
                 */
                System.out.println("保存日志,停止程序");
                e.printStackTrace();
            }
        }
    }

    private void throwInMethod() throws InterruptedException {
       Thread.sleep(2000);
    }

    public static void main(String[] args) throws InterruptedException {
        Thread thread = new Thread(new RightWayStopThreadInProd());
        thread.start();
        Thread.sleep(1000);
        thread.interrupt();
    }
}
